<?php

class CameraController extends Controller {
	
	/**
	 * @var string the default layout for the views.
	 * Defaults to '//layouts/column2', meaning using two-column layout.
	 * See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl',
			'postOnly + delete',
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array(
					'index',
					'view',
					'upload',
					'monitor',
					'show',
					'getTime',
				),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('create', 'update', 'admin', 'delete'),
				'users'=>array('@'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array('model'=>$this->loadModel($id)));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view'
	 * page.
	 */
	public function actionCreate() {
		$model = new Camera;

		// $this->performAjaxValidation($model);

		if (isset($_POST['Camera'])) {
			$model->attributes = $_POST['Camera'];
			if ($model->save()) {
				$this->redirect(array('view', 'id'=>$model->id));
			}
		}

		$this->render('create', array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view'
	 * page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		// $this->performAjaxValidation($model);

		if(isset($_POST['Camera'])) {
			$model->attributes = $_POST['Camera'];
			if($model->save()) {
				$this->redirect(array('view', 'id'=>$model->id));
			}
		}

		$this->render('update', array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin'
	 * page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		$this->loadModel($id)->delete();

		if (!isset($_GET['ajax'])) {
			$isSet = isset($_POST['returnUrl']);
			$this->redirect($isSet ? $_POST['returnUrl'] : array('admin'));
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Camera');
		$this->render('index', array('dataProvider'=>$dataProvider));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Camera('search');
		$model->unsetAttributes();
		if (isset($_GET['Camera'])) {
			$model->attributes = $_GET['Camera'];
		}
		
		$this->render('admin', array('model'=>$model));
	}

	/**
	 * Returns the data model based on the primary key given in the GET
	 * variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Camera::model()->findByPk($id);
		if ($model === null) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'camera-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionMonitor($min=1, $max=1, $delay=1000,
			$sequences=null) {
		Yii::app()->theme = 'camera';
		$this->layout = '//layouts/column1';
		
		if ($sequences) {
			$a = explode(',', $sequences);
			$sequences = array();
			foreach ($a as $each) {
				$sequences[] = trim($each);
			}
		} else {
			$sequences = array();
			for ($i = $min; $i <= $max; $i++) {
				$sequences[] = $i;
			}
		}
		$data = array('sequences'=>$sequences, 'delay'=>$delay);
		$this->render('monitor', $data);
	}
	
	public function actionShow($id) {
		header('Content-type: image/jpeg');
		$camera = new Camera;
		$camera->sequence = $id;
		if ($camera->imageExists) {
			$imageFile = $camera->imageFile;
		} else {
			$imageFile = $camera->defaultImageFile;
		}
		$image = imagecreatefromjpeg($imageFile);
		echo imagejpeg($image);
		Yii::app()->end();
	}
	
	public function actionUpload($id) {
		$status = 'HTTP/1.1 406 Not Acceptable';
		$success = false;
		
		if (isset($_FILES['file'])) {
			$file = CUploadedFile::getInstanceByName('file');
			$camera = new Camera;
			$camera->sequence = $id;
			if ($file->saveAs($camera->imageFile)) {
				$status = 'HTTP/1.1 200 OK';
				$success = true;
			}
		}
		
		header($status);
		header('Content-type: application/json');
		$data = array('success'=>$success);
		echo CJSON::encode($data);
		Yii::app()->end();
	}
	
	public function actionGetTime() {
		header('Content-type: application/json');
		$sequence = $_GET['sequence'];
		$json = array(
			'sequence'=>$sequence,
			'time'=>'N/A',
		);
		
		$camera = new Camera;
		$camera->sequence = $sequence;
		if ($camera->imageExists) {
			$json['time'] = $camera->modifiedTime;
		}
		
		echo CJSON::encode($json);
		Yii::app()->end();
	}

}
